// 簿记管理页面
import { Form } from '@ant-design/compatible';

import '@ant-design/compatible/assets/index.css';
import { Row, Col, message, Spin, Dropdown, Menu } from 'antd';
import { connect } from 'dva';
import _ from 'lodash';
import moment from 'moment';
import React from 'react';

import { exportFile } from '@/src/utils/commonFunc';

import DetailC from './detailC';
import styles from './index.less';
import QueryC from './query';
import RollOverdetail from './rollOverdetail';
import UploadHistory from './UploadHistory';

import { ContentPackage, PrimaryC, PrimaryGhostC, TableC, ModalC, ProductGroupSepC, SelectC, UploadC } from '../../../comps';
import uploadDataType from '../../../utils/enumeratedValues/ComStar.js';

const FormItem = Form.Item;

@Form.create()
class BookkeepingMnt extends React.Component {
  state = {
    pageStatus: 1, // 页面状态 1-列表页  2-详情页
    businessType: -1, // 当前选中的业务类型
    currentPage: 1, // 当前页码
    pageSize: 10, // 一页数量
    total: 0, // 数据总数
    isReset: false, // 标记是否点击了“重置”后未重新查询
    queryItems: {
      // 存储最新的查询条件
      search_GTE_createdTs: moment().subtract(1, 'months'),
      search_LTE_createdTs: moment(),
    },
    uploadShow: false, // 模板上传模态框
    columns: [],
    dataSource: [],
    visible: false, // 模态框
    detailObj: {}, // 传入模态框数据
    loadingFile: false, // 上传loading
    name: '',
    fileList: [],
    productId: '',
    portfoliold: '',
    visible1: false,
    uploadType: '',
    bookingFlag: false,
    uploadHistoryOpen: false,
  };

  componentDidMount() {
    if (sessionStorage.getItem('bookkeepingManagement')) {
      const data = sessionStorage.getItem('bookkeepingManagement');
      sessionStorage.removeItem('bookkeepingManagement');
      if (data) {
        const obj = JSON.parse(data);
        // 查询变量赋值 以及表单赋值
        const query = {
          search_IN_method: '0;1',
          userId: localStorage.getItem('antd-pro-userId'),
          ...obj,
        };
        setTimeout(() => {
          this.queryRef?.state?.RANGEDATERef.props.form.setFieldsValue({
            search_GTE_createdTs: moment(obj.search_GTE_createdTs),
            search_LTE_createdTs: moment(obj.search_LTE_createdTs),
          });
        }, 300);
        this.onQuery(query);
      }
      return; // 从用户视图跳转过来 则不继续
    }
    const query = {
      search_GTE_createdTs: moment().subtract(1, 'months').format('YYYY-MM-DD'),
      search_IN_method: '0;1',
      search_LTE_createdTs: moment().format('YYYY-MM-DD'),
      userId: localStorage.getItem('antd-pro-userId'),
    };
    this.onQuery(query);
  }

  UNSAFE_componentWillReceiveProps() {
    // 从用户视图跳转过来
    const data = sessionStorage.getItem('bookkeepingManagement');
    sessionStorage.removeItem('bookkeepingManagement');
    if (data) {
      const obj = JSON.parse(data);
      // 查询变量赋值 以及表单赋值
      const query = {
        search_IN_method: '0;1',
        userId: localStorage.getItem('antd-pro-userId'),
        ...obj,
      };
      setTimeout(() => {
        this.queryRef?.state?.RANGEDATERef.props.form.setFieldsValue({
          search_GTE_createdTs: moment(obj.search_GTE_createdTs),
          search_LTE_createdTs: moment(obj.search_LTE_createdTs),
        });
      }, 300);
      this.onQuery(query);
    }
  }

  componentWillUnmount() {}
  // 详情确定
  onOkAccount = (record) => {
    const temp = _.cloneDeep(record);
    temp.isEdit = true;
    this.setState({
      visible: true,
      detailObj: temp,
    });
  };
  // 获取表格数据
  getList = () => {
    const { queryItems, pageSize, currentPage } = this.state;
    this.props.dispatch({
      type: 'bookkeepingMntM/getList',
      payload: {
        ...queryItems,
        current: currentPage,
        pageSize,
      },
      callback: (data) => {
        if (data && data.dataSource.length) {
          this.changeColumns(data.columns);
          data.dataSource?.map(item=>{
           if(item.type=='5') item.confirm=item.trade5.confirm;//场外基金确定按钮显示
          })
          this.setState({
            columns: data.columns,
            dataSource: data.dataSource,
            currentPage: data.pageInfo.currentPage,
            total: data.pageInfo.total,
            pageSize: data.pageInfo.pageSize,
          });
        } else {
          this.setState({
            dataSource: [],
            columns: [],
            total: 0,
            currentPage: 1,
            pageSize: 10,
          });
        }
      },
    });
  };
  // 添加操作列
  changeColumns = (columns) => {
    columns.map((v) => {
      if (v.dataIndex === 'productName') v.render = (text, record) => `${record.productCode}-${record.productName}`;
      if (v.dataIndex === 'portfolioInfoName') v.render = (text, record) => `${record.portfolioInfoCode}-${record.portfolioInfoName}`;
    });
    if (columns.length && columns[columns.length - 1].title != '操作') {
      columns.push({
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        fixed: 'right',
        width: 140,
        operates: [
          {
            // 场外基金展示，交收状态时已交收和到期交收时不可点击
            title: '确定',
            onClick: (record) => {
              this.onOkAccount(record);
            },
            rules: {
              hide: {
                items: [{ key: 'type', value: ['5'], relation: ['!='] }],
              },
              disabled: {
                items: [
                  {
                    key: 'instructionStatus',
                    value: ['7', '8'],
                    relation: ['=', '='],
                  },
                  {
                    key: 'direction',
                    value: ['6'],
                    relation: ['='],
                  },
                  {
                    key: 'confirm',
                    value: ['1'],
                    relation: ['='],
                  },
                ],
                relation: 'or',
              },
            },
          },
          {
            // 债券网下申购展示，点击中签确定后不可点击
            title: '中签',
            onClick: (record) => {
              this.onOkAccount(record);
            },
            rules: {
              hide: {
                items: [{ key: 'type', value: ['17'], relation: ['!='] }],
              },
              disabled: {
                items: [{ key: 'bondOffStatus', value: ['1'], relation: ['='] }],
                relation: 'or',
              },
            },
          },
          {
            title: '详情',
            onClick: (record) => {
              this.detailAccount(record);
            },
          },
          {
            // 交收状态时已交收和到期交收时不可点击
            title: '删除',
            onClick: (record) => {
              this.deleteAccount(record.id, record);
            },
            rules: {
              disabled: {
                items: [
                  {
                    key: 'instructionStatus',
                    value: ['7', '8'],
                    relation: ['=', '='],
                  },
                ],
                relation: 'or',
              },
            },
          },
        ],
      });
    }
  };

  // 详情点击
  detailAccount = (record) => {
    this.setState({
      visible: true,
      detailObj: record,
    });
  };
  // 删除点击
  deleteAccount = (id, record) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'bookkeepingMntM/delTrade',
      payload: {
        id,
      },
      callback: (res) => {
        if (res === 'success') {
          if (record.trade7?.orderSide == 3) {
            message.warning('请确保标准券数量可以满足融资回购的需求，若删除该条质押后，融资回购的标准券数量不足，将会出现可用为负的情况。');
          }
          this.getList();
        }
      },
    });
  };

  // 响应查询
  onQuery = (query) => {
    const queryItems = {
      params: query,
    };
    this.setState({ queryItems, isReset: false, currentPage: 1 }, () => this.getList());
  };

  // 响应重置
  onClear = () => {
    this.setState({ isReset: true, currentPage: 1, pageSize: 10 });
  };

  rollOverOpen = () => {
    this.setState({ pageStatus: 3 });
  };
  // 刷新
  refresh = () => {
    const { isReset } = this.state;
    if (isReset) {
      message.warning('查询条件已重置，请重新查询！');
    } else {
      this.getList();
    }
  };

  // 下载
  download = (fileName) => {
    exportFile('api/v1/bookkeepingImport/downloadTemplate', { fileName });
  };

  // 上传
  upload = () => {
    this.setState({
      uploadShow: true,
    });
  };
  import = (productId, portfoliold, type) => {
    const { fileList } = this.state;
    const { dispatch } = this.props;
    const formData = new FormData();
    fileList.forEach((file) => {
      formData.append('file', file);
      formData.append('productId', productId);
      formData.append('portfolioId', portfoliold);
      formData.append('type', type);
      formData.append('fileName', file.title);
      formData.append('fileId', file.value);
    });
    const payloadForCurrent = {
      productId,
      portfolioId: portfoliold,
      type,
      fileId: fileList[0].value,
      fileName: fileList[0].title,
    };
    this.setState({
      loadingFile: true,
      name: '导入中...',
    });

    dispatch({
      type: 'bookkeepingMntM/uploadFile',
      payload: {
        file: payloadForCurrent,
        // url: '/bondTrade/import',
      },
      callback: (res) => {
        if (res.code == 0) {
          this.setState({
            uploadShow: false,
            fileList: [],
            productId: undefined,
            portfoliold: undefined,
          });
          message.success('上传请求已提交。请点击【上传记录】按钮，查看上传状态；请点击【刷新】按钮，在簿记结果列表中获取导入结果，最长等待时长为1分钟', 4);
          this.refresh();
        } else if (res.code == -1) {
          message.error(`簿记上传失败: ${res.msg}`);
        } else {
          message.error(`簿记上传错误: ${res.msg}`);
        }
        this.setState({
          loadingFile: false,
          name: '',
          fileList: [],
        });
      },
    });
  };
  // 新增成功
  addNewSucc = () => {
    this.setState({ pageStatus: 1 });
    this.refresh();
  };

  // 组合改变
  groupOnChange = (value) => {
    // 抛出组合id
    let val;
    if (value) val = value.key;
    this.setState({
      portfoliold: val,
    });
  };
  // 产品改变
  productOnChange = (value) => {
    let val;
    if (value) val = value.key;
    this.setState({
      productId: val,
    });
  };
  // 簿记模板上传确认
  handleOk = () => {
    const { form } = this.props;
    const { fileList, productId, portfoliold, uploadType } = this.state;
    fileList.length ? form.setFieldsValue({ upload: true }) : form.setFieldsValue({ upload: undefined });

    form.validateFields(['upload', 'type'], (err) => {
      if (!err) {
        this.import(productId, portfoliold, uploadType);
      }
    });
  };
  // 改变visible
  changeVisible = (msg) => {
    this.setState({
      visible: msg,
    });
  };
  addanCancel = () => {
    this.setState({ visible1: false });
  };
  // 表格页码排序改变调用
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    if (this.state.isReset) {
      // 判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      this.setState({
        isReset: false,
      });
      return;
    }
    this.setState(
      {
        currentPage: current,
        pageSize,
      },
      () => {
        this.getList();
      },
    );
  };

  // 簿记上传类型改变
  uploadTypeOnChange = (e) => {
    this.setState({ uploadType: e });
  };
  // 导出
  export = () => {
    const exportData = {
      current: 1,
      pageSize: 10000000,
    };
    const params = _.cloneDeep(this.state.queryItems.params);
    exportData.params = JSON.stringify(params);
    exportFile('api/v1/tradeOperate/exportTrades', exportData);
  };

  uploadHistory = () => {
    this.setState({
      uploadHistoryOpen: true,
    });
  };
  handleMenuClick = (e) => {
    this.download(e.key);
  };
  dataExportMenu = () => (
    <Menu onClick={this.handleMenuClick}>
      <Menu.SubMenu key='LocalCurrencyFrontSys' title='本币前台系统'>
        <Menu.Item key='本币前台系统交易导入模板 - 银行间质押式回购.xls'>银行间质押式回购</Menu.Item>
        <Menu.Item key='本币前台系统交易导入模板 - 银行间债券.xls'>银行间间债券</Menu.Item>
        <Menu.Item key='本币前台系统交易导入模板 - 理财直融.xls'>理财直融</Menu.Item>
        {/* <Menu.SubMenu title="场外基金" key="OTC-funds">
          <Menu.Item key="本币前台系统交易导入模板 - 场外货币基金.xls">货币基金</Menu.Item>
          <Menu.Item key="本币前台系统交易导入模板 - 场外净值型基金.xls">净值型基金</Menu.Item>
        </Menu.SubMenu> */}
      </Menu.SubMenu>
      <Menu.SubMenu key='PBSys' title='PB系统'>
        <Menu.Item key='PB成交信息导入模板.xls'>场内ETF基金</Menu.Item>
      </Menu.SubMenu>
    </Menu>
  );
  sureUploadHistory = () => {
    this.setState({
      uploadHistoryOpen: false,
    });
  };

  render() {
    const { pageStatus, uploadShow, columns, dataSource, visible, total, currentPage, pageSize } = this.state;
    const {
      form: { getFieldDecorator },
      loading,
    } = this.props;
    const that = this;
    const modalProps = {
      destroyOnClose: true,
      visible: uploadShow,
      maskClosable: false,
      title: '簿记上传',
      width: 700,
      wrapClassName: 'uplaodFile',
      confirmLoading: loading.effects['bookkeepingMntM/uploadFile'] === true,
      onCancel() {
        that.setState({
          uploadShow: false,
          fileList: [],
        });
      },
      onOk: () => {
        this.handleOk();
      },
    };

    return (
      <ContentPackage
        title='簿记查询'
        contentHtml={
          <div>
            {this.state.uploadHistoryOpen && (
              <UploadHistory open={this.state.uploadHistoryOpen} onOk={this.sureUploadHistory} onCancel={() => this.setState({ uploadHistoryOpen: false })} />
            )}
            <div style={{ display: pageStatus == 1 ? 'block' : 'none' }}>
              <QueryC onQuery={this.onQuery} onClear={this.onClear} bookkeepingType='1' onRef={(ref) => (this.queryRef = ref)} />

              <div style={{ marginTop: '10px' }} />
              <PrimaryC
                title='簿记上传'
                onClick={this.upload}
                style={{ marginRight: '10px' }}
                helper='目前仅支持ETF，银行间回购，银行间债券，理财直融，场外净值型基金，场外货币型基金指令类型上传，其它指令类型，敬请期待！'
              />
              <PrimaryC title='上传记录' onClick={this.uploadHistory} style={{ marginRight: '10px' }} />

              <PrimaryC title='转仓' onClick={this.rollOverOpen} />
              <div style={{ float: 'right' }}>
                <PrimaryGhostC title='刷新' onClick={this.refresh} style={{ marginRight: '10px' }} />
                <PrimaryGhostC title='导出' onClick={this.export} style={{ marginRight: '10px' }} />

                <Dropdown overlay={this.dataExportMenu} trigger={['click']}>
                  <PrimaryGhostC title='模板下载' style={{ marginRight: '10px' }} icon='down' />
                </Dropdown>
              </div>
              <div style={{ marginTop: '10px' }}>
                <TableC
                  columns={columns}
                  loading={loading.effects['bookkeepingMntM/getList']}
                  dataSource={dataSource}
                  current={currentPage}
                  pageSize={pageSize}
                  total={total}
                  scroll={{ x: 'max-content' }}
                  selfScrollY
                  rowKey='id'
                  pagination
                  onChange={this.handleTableChange}
                />
              </div>
              {visible && <DetailC visible={this.state.visible} detailObj={this.state.detailObj} changeVisible={this.changeVisible} refresh={this.refresh} />}
              {/* {visible1 && <ModalC
                        visible={visible1}
                        title={'确定'}
                        onCancel={this.addanCancel}
                        maskClosable={false}
                        footer={null}
                        width={1200}
                    ><div style={{ height: '350px' }}><FundTrade type={'3'} info={this.state.detailObj ? this.state.detailObj : {}} /></div></ModalC>} */}
              {uploadShow && (
                <ModalC {...modalProps}>
                  <Spin spinning={this.state.loadingFile == true}>
                    <div className={styles.content}>
                      <Form>
                        <Row>
                          <Col span={24}>
                            <ProductGroupSepC
                              form={this.props.form}
                              title={['产品', '组合']}
                              authority='write'
                              multipleGroup={false}
                              dataIndex={['productid', 'portfolioid']}
                              // rules={[[{required: true, message: "请选择产品"}], [{required: true, message: "请选择组合"}]]}
                              groupOnChange={(e) => this.groupOnChange(e)}
                              productOnChange={(e) => this.productOnChange(e)}
                              allowClear
                              positionBody
                            />
                          </Col>
                        </Row>
                        <Row>
                          <Col span={12}>
                            <SelectC
                              positionBody
                              form={this.props.form}
                              title='类型'
                              dataIndex='type'
                              rules={[{ required: true, message: '请选择类型' }]}
                              allowClear
                              dataSource={uploadDataType}
                              onChange={this.uploadTypeOnChange}
                            />
                          </Col>
                          <Col span={12}>
                            <FormItem label='上传附件' style={{ marginLeft: 24, display: 'flex' }}>
                              {getFieldDecorator('upload', {
                                rules: [
                                  {
                                    required: true,
                                    message: '请上传附件',
                                  },
                                ],
                              })(
                                <UploadC
                                  title='选择'
                                  type={1}
                                  accept='.xlsx,.xls'
                                  value={this.state.fileList?.map((x) => ({ title: x.name, value: x.uid }))}
                                  showUploadList
                                  isDown={false}
                                  max={1}
                                  onUpload={(e) => {
                                    this.setState({ fileList: [e] });
                                  }}
                                  onRemove={() => this.setState({ fileList: [] })}
                                />,
                              )}
                            </FormItem>
                          </Col>
                        </Row>
                        <Row>
                          <div className={styles.needKnow}>
                            <FormItem label='上传须知' style={{ margin: '0 16px' }}>
                              <div className='line'>1. 选择的【类型】需与【上传附件】格式保持一致；</div>
                              <div className='line'>2. 未选择【产品/组合】时，会将附件中的数据簿记到列表指定产品的根组合下；</div>
                              <div className='line'>3. 选择了【产品/组合】时，会将附件中的数据簿记到指定的组合下；</div>
                              <div className='line'>4. 上传完毕，请在“上传记录”中查看上传状态，确保已解析成功；</div>
                              <div className='line'>5. 仅支持上传当天交易的数据。</div>
                            </FormItem>
                          </div>
                        </Row>
                      </Form>
                    </div>
                  </Spin>
                </ModalC>
              )}
            </div>

            {pageStatus == 3 && (
              <div>
                <RollOverdetail onClose={() => this.setState({ pageStatus: 1 })} onRefresh={this.addNewSucc} />
              </div>
            )}
          </div>
        }
      />
    );
  }
}

export default connect(({ tradeBook, userM: user, bookkeepingMnt, loading, tradeManageM }) => ({
  tradeBook,
  user,
  bookkeepingMnt,
  loading,
  tradeManageM,
}))(BookkeepingMnt);
